package com.app.controller;


import cn.hutool.core.util.StrUtil;
import com.app.common.ScaleTool;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.EnterpriseVo;
import com.app.vo.IntermediaryVo;
import com.app.vo.ScaleVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Controller
@RestController
@Data
public class IntermediaryController {


    @Autowired
    IntermediaryService intermediaryService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    JobPublishService jobPublishService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    IndustryService industryService;
    @Autowired
    ConfigService configService;
    @Autowired
    UserService userService;


    //新增修改
    @PostMapping("/editIntermediary")
    @ResponseBody
    public Result<Object> groupItemExp(HttpServletRequest request, @RequestBody IntermediaryModel model) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        if (model.getId() != null && model.getId() > 0) {
            intermediaryService.update(model);
        } else {
            model.setCrtTime(CommonHelp.getNowTimestamp());
            intermediaryService.insert(model);
        }
       int adminIsExist =  insertAdminUser(model);
        if(adminIsExist==0)
        {
            return Result.error(405, "管理后台用户名已存在");
        }
        UserModel userModel = userService.getUserByMobile(model.getMobile());
        if(userModel==null)
        {
            userModel = new UserModel();
            userModel.setUserName(model.getMobile());
            userModel.setMobile(model.getMobile());
            userModel.setFaceUrl(model.getLogo());
            userModel.setZId(model.getId());
            userModel.setCrtTime(CommonHelp.getNowTimestamp().toString());
            userService.insert(userModel);
        }else{
            userModel.setZId(model.getId());
            userModel.setUserName(model.getMobile());
            userModel.setMobile(model.getMobile());
            userModel.setFaceUrl(model.getLogo());
            userModel.setUpTime(CommonHelp.getNowTimestamp().toString());
            userService.update(userModel);
        }

        return Result.success("操作成功");
    }

    public int insertAdminUser(IntermediaryModel model)
    {

        if (model.getId() == 0) {
            AdminUserModel adminUserModel = adminUserService.getUserByName(model.getUserName());
            if (adminUserModel != null) {
                return 0;
            }
            adminUserModel = new AdminUserModel();
            adminUserModel.setUserName(model.getUserName());
            String keyWord = AESTool.dealAESEncrypt("123456","hwsc_pass");
            adminUserModel.setPassWord(keyWord);
            adminUserModel.setUserType(2);
            adminUserModel.setIntermediaryId(model.getId());
            adminUserService.insert(adminUserModel);
        } else {
            AdminUserModel adminUserModel1 = adminUserService.getUserByIntermediaryId(model.getId());
            if(adminUserModel1 == null)
            {
                adminUserModel1 = new AdminUserModel();
                adminUserModel1.setUserName(model.getUserName());
                String keyWord = AESTool.dealAESEncrypt("123456","hwsc_pass");
                adminUserModel1.setPassWord(keyWord);
                adminUserModel1.setUserType(2);
                adminUserModel1.setIntermediaryId(model.getId());
                adminUserService.insert(adminUserModel1);
            }else{
                adminUserModel1.setUserName(model.getUserName());
                adminUserService.update(adminUserModel1);
            }
        }
        return 1;
    }

    /**
     * 获取中介机构列表
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/getIntermediaryList")
    public Result<Object> getIncubatorsList(HttpServletRequest request, IntermediaryModel model) {
        IntermediaryVo vo = intermediaryService.getListByModel(model);
        return Result.success(vo);
    }

    // 手机号码前二后二脱敏
    public static String mobileEncrypt(String mobile) {
        if (StringUtils.isEmpty(mobile) || (mobile.length() != 11)) {
            return mobile;
        }
        return mobile.replaceAll("(\\w{2})\\w*(\\w{2})", "$1******$2");
    }

    /**
     * 获取中介机构详情
     *
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/getIntermediaryById")
    public Result<Object> getIncubatorsList(HttpServletRequest request, Integer id, Integer type, Integer page, Integer limit) {
        IntermediaryModel intermediaryModel = intermediaryService.getModelById(id);
        for (ScaleVo vo : ScaleTool.SCALE_VO_LIST) {
            if (intermediaryModel.getScale() != null) {
                if (intermediaryModel.getScale() == vo.getId()) {
                    intermediaryModel.setScaleText(vo.getData());
                }
            }
        }
        if (StrUtil.isNotEmpty(intermediaryModel.getMobile())) {
            intermediaryModel.setDesensitizationMobile(mobileEncrypt(intermediaryModel.getMobile()));
        }
        AdminUserModel adminUserModel1 = adminUserService.getUserByIntermediaryId(intermediaryModel.getId());
        intermediaryModel.setUserName(adminUserModel1.getUserName());
        if (type != null && type > 0) {
            List<JobPublishModel> jobList = jobPublishService.getListByIntermediaryId(intermediaryModel.getId());
            if (jobList != null) {
                StringBuilder ids = new StringBuilder();
                for (int i = 0; i < jobList.size(); i++) {

                    ids.append(jobList.get(i).getEnrollId()).append(",");
                }
                String str[] = ids.toString().split(",");
                EnterpriseModel model = new EnterpriseModel();
                model.setPage(page);
                model.setLimit(limit);
                model.setIds(str);
                Page<EnterpriseModel> modelPage = enterpriseService.findModelAll(model);
                List<EnterpriseModel> modelList = modelPage.getRecords();
                for (int i = 0; i < modelList.size(); i++) {
                    int fairCount = jobPublishService.getModelCountByEid(modelList.get(i).getId());
                    modelList.get(i).setFairCount(fairCount);
                    modelList.get(i).setScaleName("暂无规模");
                    for (int j = 0; j < ScaleTool.SCALE_VO_LIST.size(); j++) {
                        if (modelList.get(i).getScaleId() != null && modelList.get(i).getScaleId() == ScaleTool.SCALE_VO_LIST.get(j).getId()) {
                            modelList.get(i).setScaleName(ScaleTool.SCALE_VO_LIST.get(j).getData());
                        }
                    }

                    if (StringTool.isNotEmpty(modelList.get(i).getEnterpriseType())) {
                        IndustryModel industryModel = industryService.getModelByCode(modelList.get(i).getEnterpriseType());
                        modelList.get(i).setEnterpriseName(industryModel.getIndustryName());
                    } else {
                        modelList.get(i).setEnterpriseName("暂无行业");
                    }
                }
                EnterpriseVo vo = new EnterpriseVo();
                vo.setList(modelList);
                vo.setCount((int) modelPage.getTotal());
                intermediaryModel.setEnterpriseVo(vo);
            }
        }
        return Result.success(intermediaryModel);
    }

    /**
     * 获取中介机构关联公司
     *
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/getEntListByIntermediarId")
    public Result<Object> getEntListByIntermediaryId(HttpServletRequest request, Integer id) {
        IntermediaryModel model = intermediaryService.getModelById(id);

        return Result.success(model);
    }


}
